<template>
	<div class='content'>

		<section>
			<div class="profile_page">
				<head-top :go-back='goBack' :head-title="profiletitle"></head-top>
			</div>
		</section>
		<div style="height: 100%;padding-top: 2px;">
			<van-search v-model="value" show-action @search="onSearch" placeholder="请输入搜索关键词">
                <template #action>
                    <div @click="onSearch">搜索</div>
                </template>
            </van-search>
			<div class="flex orgSelect" style="margin-top: 12px;">
				<!--<van-cell is-link  @click="selectOrg()"><span class="borderLine"></span><span class="lineTetx">{{text}}</span></van-cell>-->
				<van-cell is-link   @click="showTreepickerAction"><span class="borderLine"></span><span class="lineTetx">{{text}}</span></van-cell>
			</div>
			<div class="personList"  style="height: calc(100vh - 180px);">
				<!-- <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :offset="offset">
							  <div class="list" @click="toPage()">
										<img src="@/assets/images/img/man_moren.png" alt="">
										<div>
											<p>姓名</p>
											<p>部门</p>
										</div>
								</div>
				</van-list> -->
                <van-list
                        v-model="loading"
                        :finished="finished"
                        finished-text="没有更多了"
                        @load="onLoad"
                        :offset="offset"
                        :immediate-check="imCheck"
                >
                    <div class="list" v-for="personList in personLists" :key="personList.id"  @click="toPage(personList.id)">
                            <img :src="personList.photo|imgStr" alt="">
                            <div>
                                <p>{{personList.name}}</p>
                                <p>{{personList.deptId | translate}}</p>
                            </div>
                    </div>
                </van-list>
			</div>
		</div>
		<van-popup v-model="pickershow" position="bottom">
			<van-picker id="picker"  show-toolbar :title="title" value-key="name" :columns="columns" @cancel="onCancel" @confirm="onConfirm" />
		</van-popup>

        <van-popup
                v-model="showTreePicker"
                :style="{ height: '60%' }"
                position="bottom"
        >
            <div class="van-picker__toolbar toobar" style="position: fixed;width: 100%;background: #fff;
    z-index: 101;">
                <button @click="onCancelTree" type="button" class="van-picker__cancel">
                    取消</button
                ><button
                    @click="onConfirmTreePicker"
                    type="button"
                    class="van-picker__confirm"
            >
                确认
            </button>
            </div>

            <section class="tree" style="z-index: 100">
                <ul v-for="item in trips" :key="item.id">
                    <TreeView :data="item" :if-open="searchOpen"></TreeView>
                </ul>
            </section>
        </van-popup>
	</div>
</template>

<script>
	var that;
    let Base64 = require('js-base64').Base64
	import headTop from '@/components/header/head';
    import TreeView from "@/components/TreeView/TreeView";
    import {mapState, mapMutations} from 'vuex'
	import {
		managerOrgs,
		managerPerson,
		getOrg
	} from '@/service/getData';
	import {
		getStore,
        contextRoot,
        toTreeData
	} from '@/assets/config/mUtils';
	import {
		Dialog,
		Toast
	} from 'vant';
	export default {
		data() {
			return {
				profiletitle: '经理自助',
				goBack: true,
				CHECK_TIME: new Date().getTime().toString(),
				app_userId: '',
				loading: false,
				finished: false,
                showTreePicker: false,
				pageIndex: 0,
				offset: 0,
				columns:[],
				title:'选择机构',
				pickershow:false,
				value:'',
				text:'',
				personLists:[],
				orgList:[],
                imCheck:false,
                trips:[],
                searchOpen: false,
			}
		},
		created() {
			that = this;
			this.app_userId = getStore('user_id');
                      managerOrgs().then(org =>{
                          this.orgList = org.data.orgList;
                          this.columns = org.data.orgList;
                          this.trips = this.jsonToTree(org.data.orgList,'orgId','superId')
                          this.orgId = this.columns[0].orgId;
                          this.text = this.columns[0].name;
                          this.pickershow = false;
                          this.onLoad();
          //                managerOrgs().then(res=>{
          //                    console.log(this.columns,"33333");
          //                    this.text = this.columns[0].name;
          //                    this.pickershow = false;
          ////                    managerPerson({orgId:this.columns[0].orgId}).then(res=>{
          ////                        this.personLists = res.data.personList;
          ////                    })
          //                })
                      })
		},
		filters:{
			translate(val){
				var arr = that.orgList.filter(item => item.orgId == val);
				if(arr[0]){
					return arr[0].name
				}else{
					return ""
				}
				
			},
            imgStr(val){
                var interfaceUrl = contextRoot();
                if(!val){
                        var imgUrl =  require('@/assets/images/img/man_moren.png');
                        return imgUrl;
                }else {
                    var imgUrl = interfaceUrl+ '/api/file/att/download?app_userId='+getStore('user_id')+'&fileId='+val.base64Encode();
                    return imgUrl
                }
            }
		},
		mounted() {
			//getOrg().then(org =>{

			//})
			

		},
		props: ['imgSrc', 'menuTitle'],
		components: {
			headTop,
            TreeView
		},
        computed:{
            ...mapState({
                selectedTreeItem:state=>state.selectedTreeItem,
            })
        },
		methods: {
          jsonToTree(jsonData, id, pid) {
            let result = [],
                temp = {};
            for (let i = 0; i < jsonData.length; i++) {
              temp[jsonData[i][id]] = jsonData[i]; // 以id作为索引存储元素，可以无需遍历直接定位元素
            }
            for (let j = 0; j < jsonData.length; j++) {
              let currentElement = jsonData[j];
              let tempCurrentElementParent = temp[currentElement[pid]]; // 临时变量里面的当前元素的父元素
              if (tempCurrentElementParent) {
                // 如果存在父元素
                if (!tempCurrentElementParent["children"]) {
                  // 如果父元素没有chindren键
                  tempCurrentElementParent["children"] = []; // 设上父元素的children键
                }
                tempCurrentElementParent["children"].push(currentElement); // 给父元素加上当前元素作为子元素
              } else {
                // 不存在父元素，意味着当前元素是一级元素
                result.push(currentElement);
              }
            }
            return result;
          },
		    //搜索
            onSearch(){
                this.personLists = [];
                this.pageIndex = 0;
                this.finished = false;
                this.loading = true;
                this.onLoad();
            },
			onLoad() {
				var data = {};
				data.pageIndex = this.pageIndex;
				data.orgId = this.orgId;
				if(this.value == ""){
                    data.filterStr = '';
                }else {
                    data.filterStr = 'name:'+ this.value+'##';
                }
				data.pageSize = 16;
                managerPerson(data).then(res => {
 					// 加载状态结束
 					this.loading = false;
 					this.offset = 10 * this.pageIndex;
 					if (this.personLists.length < res.data.total) {
 						this.personLists = this.personLists.concat(res.data.personList);
 					} else {
 						this.finished = true;
 					}
 				});
				this.pageIndex += 1;
			},
			selectOrg(){
				this.pickershow = true;
			},
			onConfirm(val){
				this.text = val.name;
				this.pickershow = false;
//				managerPerson({orgId:val.orgId}).then(res=>{
//					this.personLists = res.data.personList;
//				});
                this.orgId = val.orgId;
                this.personLists = [];
                this.pageIndex = 0;
                this.finished = false;
                this.loading = true;
                this.onLoad();
			},
			onCancel(){
                this.pickershow = false;
			},
			toPage(id){
				this.$router.push({path:'/selfManageDetail', query: {id}});
			},
            /*下拉树选择取消*/
            onCancelTree() {
                this.showTreePicker = false;
            },
            /*下拉树选择确认*/
            onConfirmTreePicker() {
                //选择地区
                this.showTreePicker = false;
                console.log(this.selectedTreeItem);
                this.text = this.selectedTreeItem.name;
                this.orgId = this.selectedTreeItem.orgId;
                this.personLists = [];
                this.pageIndex = 0;
                this.finished = false;
                this.loading = true;
                this.onLoad();
                //let selectReason = this.selectedTreeItem;
            },
            showTreepickerAction(){
                this.showTreePicker = true;
            },
		}
	}
</script>
<style lang="scss" scoped>
    @import '../../assets/style/mixin';
    @import '../../assets/style/public';
	.borderLine {
		border-left: 2px solid #5082d8;
		margin-right: 6px;
	}

	.lineTetx {
		color: #333;
	}
	.list{
		display: flex;
		width: 100%;
		align-items: center;
		background: #fff;
		border-bottom: 1px solid #e4e3e3;
	}
	.personList{
		margin-top: 10px;
		padding: 0 20px;
		background: #fff;
		overflow: auto;
	}
	.list img{
		width: 1.4rem;
		height: 1.4rem;
		padding: 0.5rem 1rem;
	
	}
	.list div p{
		font-size: .4rem;
		color: #333;
		margin: 0;
		line-height: 0.8rem;
	}
	.list div p:nth-of-type(1){
		font-size: .5rem;
		font-weight: bold;
		color:#5082d8 ;
	}
    .tree {
        margin-top: 44px;
        padding: 0 8px;

        span {
            &:hover {
                background: #edf0f5;
            }
        }
    }
</style>
